function BeforeSave(payload) {
  var id = Process("session.Get", "user_id");
  payload["oper_id"] = id;


  if (payload.start_date) {
    for (let key in payload) {
      if (key.startsWith('start_date.')) {
        delete payload[key];
      }
    }
    const dateString = payload.start_date.slice(0, 10);
    payload.start_date = dateString;
    console.log("task before save payload-3->", payload);
  }
  return [payload];
}


function Save1(payload) {
  console.log("task save payload-->", payload);
  if (!payload.sku) {
    throw new Exception("请提供产品的sku!", 400);
  }
  var user_id = payload.user_id;
  var sku = payload.sku;
  var task_confs = Process("models.task_conf.Get", { wheres: [{ "column": "sku", "op": "=", "value": sku }] });
  if (!task_confs || task_confs.length < 1) {
    throw new Exception("请提供产品" + sku + "任务的设置", 400);
  }
  console.log("-------------------------------");
  task_confs.forEach(item => {
    let _datestr = getDate(payload.start_date, item.day - 1)
    console.log(item.sku, item.day, _datestr);
    let t_task = Object.assign(payload, { "start_date": _datestr, "end_date": _datestr, "desc": item.desc, "points": item.points, "task_conf_id": item.id });
    Object.assign(t_task, { "title": "第" + item.day + "天" });

    let _task = Process("models.task.Get", { wheres: [{ "column": "sku", "op": "=", "value": sku }, { "column": "user_id", "op": "=", "value": user_id }, { "column": "start_date", "op": "like", "value": _datestr + "%" }] });
    console.log("____task", _task);
    if (_task && _task.length > 0) {
      throw new Exception("已经存在 sku:" + sku + " user_id:" + user_id + " start_date:" + payload.start_date + "的任务", 400);
    }
    Process("models.task.Save", t_task);
    console.log("insert task successfully", t_task);
  });
  return [task_confs.length];
}

function OnChange(query) {
  console.log("query-OnChange----->", query)
  // 进入onchange事件
  query = query || {};
  // field = query.key;
  // newVal = query.value;
  // oldVal = query.old;
  // params = query.params; // 开发者定义数据

  var device = Process("models.device.Find", query.value, {});
  console.log("query-device----->", device)
  let data = { sku: device.sku, user_id: device.user_id };
  // console.log("query-isOnLoad----->", query.isOnLoad);

  console.log("query-data----->", data)
  return { data };
}

function getDate(dateString, daysToAdd) {
  // 转换为 Date 对象
  const dateObj = new Date(dateString);
  // 添加天数
  dateObj.setDate(dateObj.getDate() + daysToAdd);
  // 格式化输出结果
  const resultDate = dateObj.toISOString().slice(0, 10);
  console.log(resultDate);
  return resultDate;
}